/* QtLua -- Lua bindings for Qt
   Copyright (C) 2011, Jarek Pelczar

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General
   Public License along with this library; if not, write to the
   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301 USA

*/

#include "qluaexception.h"
#include "qluascriptengine.h"
#include "qluascriptvalue.h"
#include <QSharedData>
#include <QPointer>
#include <QDebug>

class QLuaExceptionData : public QSharedData
{
public:
    QPointer<QLuaScriptEngine> m_engine;
    qint64 m_scriptId;
    QLuaScriptValue m_contents;

    static QLuaException makeException(QLuaScriptEngine * engine,
                                       qint64 scriptId,
                                       QLuaScriptValue contents)
    {
        QLuaException result;
        result.data = new QLuaExceptionData;
        result.data->m_scriptId = scriptId;
        result.data->m_engine = engine;
        result.data->m_contents = contents;
        return result;
    }
};

namespace QLuaInternal {

QLuaException qt_lua_MakeException(QLuaScriptEngine * engine,
                                   qint64 scriptId,
                                   QLuaScriptValue contents)
{
    return QLuaExceptionData::makeException(engine, scriptId, contents);
}

}

QLuaException::QLuaException()
{
}

QLuaException::QLuaException(const QLuaException &rhs) : data(rhs.data)
{
}

QLuaException &QLuaException::operator=(const QLuaException &rhs)
{
    if (this != &rhs)
        data.operator=(rhs.data);
    return *this;
}

QLuaException::~QLuaException()
{
}

bool QLuaException::isNull() const
{
    return !data;
}

QLuaScriptEngine * QLuaException::engine() const
{
    return data ? data->m_engine : NULL;
}

QLuaScriptValue QLuaException::what() const
{
    return data ? data->m_contents : QLuaScriptValue();
}

qint64 QLuaException::scriptId() const
{
    return data ? data->m_scriptId : -1;
}

QDebug operator << (QDebug d, const QLuaException& other)
{
    return d << "Lua Exception(" << other.what() << ")";
}
